<template>
	<div class="honors">
		<div class="page-header">
			<h1 class="page-title">人才计划 / 荣誉称号</h1>
			<p class="page-subtitle">填报您的高层次人才计划与荣誉称号信息</p>
		</div>

		<div style="margin-bottom: 20px;">
			<el-button type="success" @click="exportData">
				<el-icon><Download /></el-icon>
				导出数据
			</el-button>
			<el-button type="primary" style="margin-left: 8px;" @click="openCreate()">
				在线填报
			</el-button>
		</div>

		<el-card>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="category" label="类别" width="110" />
				<el-table-column prop="titleFullName" label="称号全称" min-width="240" show-overflow-tooltip />
				<el-table-column prop="grantingOrganization" label="授予单位" min-width="200" show-overflow-tooltip />
				<el-table-column prop="selectionDate" label="入选时间" width="120" />
				<el-table-column label="有效期" min-width="200">
					<template #default="{ row }">
						<span v-if="row.isPermanent">长期有效</span>
						<span v-else>{{ row.validFrom || '-' }} ~ {{ row.validTo || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog v-model="showDialog" :title="isEdit ? '编辑称号' : '在线填报称号'" width="720px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="类别" prop="category">
					<el-select v-model="form.category" placeholder="请选择" style="width: 100%">
						<el-option label="人才计划" value="人才计划" />
						<el-option label="荣誉称号" value="荣誉称号" />
					</el-select>
				</el-form-item>

				<el-form-item label="称号全称" prop="title_full_name">
					<el-input v-model="form.title_full_name" placeholder="如：国家杰出青年科学基金获得者" />
				</el-form-item>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="授予单位" prop="granting_organization">
							<el-input v-model="form.granting_organization" placeholder="如：国家自然科学基金委员会" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="入选时间" prop="selection_date">
							<el-date-picker
								v-model="form.selection_date"
								type="date"
								value-format="YYYY-MM-DD"
								placeholder="选择日期"
								style="width: 100%"
								:disabled-date="disableSelectionDate"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="有效期起" prop="valid_from">
							<el-date-picker
								v-model="form.valid_from"
								type="date"
								value-format="YYYY-MM-DD"
								placeholder="选择日期"
								style="width: 100%"
								:disabled="form.is_permanent"
								:disabled-date="disableValidFrom"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="有效期止" prop="valid_to">
							<el-date-picker
								v-model="form.valid_to"
								type="date"
								value-format="YYYY-MM-DD"
								placeholder="选择日期"
								style="width: 100%"
								:disabled="form.is_permanent || !form.valid_from"
								:disabled-date="disableValidTo"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="长期有效">
					<el-switch v-model="form.is_permanent" @change="handlePermanentChange" />
				</el-form-item>

				<el-form-item label="备注">
					<el-input v-model="form.notes" type="textarea" :rows="3" placeholder="可填写附加说明" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">{{ isEdit ? '保存' : '提交' }}</el-button>
			</template>
		</el-dialog>

		<!-- 查看对话框 -->
		<el-dialog v-model="showView" title="查看称号" width="600px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="类别">{{ currentRow?.category }}</el-descriptions-item>
				<el-descriptions-item label="称号全称">{{ currentRow?.titleFullName }}</el-descriptions-item>
				<el-descriptions-item label="授予单位">{{ currentRow?.grantingOrganization }}</el-descriptions-item>
				<el-descriptions-item label="入选时间">{{ currentRow?.selectionDate }}</el-descriptions-item>
				<el-descriptions-item label="有效期">
					<span v-if="currentRow?.isPermanent">长期有效</span>
					<span v-else>{{ currentRow?.validFrom || '-' }} ~ {{ currentRow?.validTo || '-' }}</span>
				</el-descriptions-item>
				<el-descriptions-item label="备注">{{ currentRow?.notes || '-' }}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="showView = false">关闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { getMyHonors, createHonor, updateHonor, deleteHonor } from '@/api/honor'

const showDialog = ref(false)
const isEdit = ref(false)
const showView = ref(false)
const currentRow = ref(null)
const formRef = ref()
const submitting = ref(false)

const form = reactive({
	category: '',
	title_full_name: '',
	granting_organization: '',
	selection_date: '',
	valid_from: '',
	valid_to: '',
	is_permanent: false,
	notes: ''
})

const rules = {
	category: [{ required: true, message: '请选择类别', trigger: 'change' }],
	title_full_name: [{ required: true, message: '请输入称号全称', trigger: 'blur' }],
	selection_date: [{ required: true, message: '请选择入选时间', trigger: 'change' }]
}

const tableData = ref([])

const openCreate = () => {
	isEdit.value = false
	Object.assign(form, { category: '', title_full_name: '', granting_organization: '', selection_date: '', valid_from: '', valid_to: '', is_permanent: false, notes: '' })
	showDialog.value = true
}

const disableValidFrom = (date) => {
	if (!date) return false
	// 如果选择了长期有效，不允许选择任何有效期
	if (form.is_permanent) return true
	// 有效期起必须不早于入选时间（入选时间要比有效期起要早 => valid_from >= selection_date）
	if (form.selection_date) {
		const sd = new Date(form.selection_date)
		return date < sd
	}
	return false
}

const disableValidTo = (date) => {
	if (!date) return false
	// 禁用：当未选择有效期起或长期有效时禁用在 UI 上通过 :disabled 控制
	if (!form.valid_from) return true
	const vf = new Date(form.valid_from)
	return date <= vf
}

const disableSelectionDate = (date) => {
	if (!date) return false
	// 入选日期必须早于有效期起 => selection_date < valid_from
	if (form.valid_from) {
		const vf = new Date(form.valid_from)
		return date >= vf
	}
	return false
}

const handlePermanentChange = (val) => {
	if (val) {
		// 选择长期有效 => 清空有效期起止
		form.valid_from = ''
		form.valid_to = ''
	}
}

watch(() => form.valid_from, (newVal) => {
	if (newVal) {
		// 选择了起始日期 => 禁用长期有效，并清空长期有效
		if (form.is_permanent) form.is_permanent = false
		// 如果有效期止已存在但不在起始之后，清空
		if (form.valid_to) {
			const vf = new Date(newVal)
			const vt = new Date(form.valid_to)
			if (vt <= vf) form.valid_to = ''
		}
	}
})

watch(() => form.selection_date, (newVal) => {
	// 如果选择了入选日期，且有效期起存在但早于入选日期，调整/清空有效期起
	if (newVal && form.valid_from) {
		const sd = new Date(newVal)
		const vf = new Date(form.valid_from)
		if (vf < sd) {
			form.valid_from = ''
			form.valid_to = ''
		}
	}
})

const loadTable = async () => {
	try {
		const res = await getMyHonors()
		const raw = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
		tableData.value = raw
	} catch (e) {
		console.error(e)
	}
}

const handleSubmit = async () => {
	try {
		if (!formRef.value) return
		await formRef.value.validate()
		// 额外校验：互斥和先后关系
		if (form.is_permanent && (form.valid_from || form.valid_to)) {
			ElMessage.error('选择长期有效后，不能设置有效期起止')
			return
		}
		if (!form.is_permanent && form.valid_from && form.valid_to) {
			const vf = new Date(form.valid_from)
			const vt = new Date(form.valid_to)
			if (vt <= vf) {
				ElMessage.error('有效期止必须在有效期起之后')
				return
			}
		}
		if (form.selection_date && form.valid_from) {
			const sd = new Date(form.selection_date)
			const vf = new Date(form.valid_from)
			if (sd >= vf) {
				ElMessage.error('入选日期必须早于有效期起')
				return
			}
		}

		submitting.value = true
		if (!isEdit.value) {
			await createHonor({
				category: form.category,
				title_full_name: form.title_full_name,
				granting_organization: form.granting_organization,
				selection_date: form.selection_date,
				valid_from: form.is_permanent ? null : (form.valid_from || null),
				valid_to: form.is_permanent ? null : (form.valid_to || null),
				is_permanent: !!form.is_permanent,
				notes: form.notes || null
			})
			ElMessage.success('提交成功')
		} else {
			await updateHonor(currentRow.value.id, {
				category: form.category,
				title_full_name: form.title_full_name,
				granting_organization: form.granting_organization,
				selection_date: form.selection_date,
				valid_from: form.is_permanent ? null : (form.valid_from || null),
				valid_to: form.is_permanent ? null : (form.valid_to || null),
				is_permanent: !!form.is_permanent,
				notes: form.notes || null
			})
			ElMessage.success('保存成功')
		}
		showDialog.value = false
		await loadTable()
	} catch (e) {
		console.error(e)
		ElMessage.error(e?.response?.data?.message || e?.message || '提交失败')
	} finally {
		submitting.value = false
	}
}

const handleView = (row) => {
	currentRow.value = row
	showView.value = true
}

const handleEdit = (row) => {
	currentRow.value = row
	isEdit.value = true
	Object.assign(form, {
		category: row.category,
		title_full_name: row.titleFullName,
		granting_organization: row.grantingOrganization,
		selection_date: row.selectionDate,
		valid_from: row.validFrom || '',
		valid_to: row.validTo || '',
		is_permanent: !!row.isPermanent,
		notes: row.notes || ''
	})
	showDialog.value = true
}

const handleDelete = async (row) => {
	try {
		await ElMessageBox.confirm('确定删除该记录吗？删除后不可恢复', '删除确认', { type: 'warning' })
		await deleteHonor(row.id)
		ElMessage.success('删除成功')
		await loadTable()
	} catch (e) {
		if (e !== 'cancel') {
			ElMessage.error(e?.response?.data || e?.message || '删除失败')
		}
	}
}

const exportData = async () => {
	const { exportData: exportUtil } = await import('@/utils/exportUtils')
	
	const filters = {}
	
	await exportUtil('talent-honors', filters, '人才荣誉列表.xlsx')
}

loadTable()
</script>

<style scoped>
.honors { }
.page-header { margin-bottom: 16px; }
.page-title { margin: 0; font-size: 20px; }
.page-subtitle { margin: 4px 0 0 0; color: #666; }
</style> 